<?php

namespace app\common\service\broadcast;

use app\admin\controller\broadcast\IpBroadcast;

/**
 * ip广播相关服务
 */
class IpBroadcastService
{

    public static $ip = "http://117.172.29.237:2000";
    public static $Authorization = "Authorization:basic YWRtaW46enlja2VqaTY2NjY=";

    /**
     * 通过ip查询ip下所有音箱设备
     */
    public static function synchronous()
    {
        $url = self::$ip . '/v1/device';
        $res = httpGet($url, self::$Authorization);
        $res = json_decode($res, true);
        if ($res['code'] == 200) {
            $data = $res['data'];
            //更新广播系统设备
            foreach ($data as $val) {
                $info = \app\common\model\broadcast\IpBroadcast::where(['code' => $val['code']])->value('id');
                if (empty($info)) {
                    \app\common\model\broadcast\IpBroadcast::create([
                        'code' => $val['code'],
                        'name' => $val['name'],
                        'dev_name' => $val['dev_name'],
                    ]);
                }
            }
        }
    }

    /**
     * ⽂本 TTS 与媒体 URL 播放接⼝
     * @param array $param 参数数组
     */
    public static function speech(array $param)
    {
        $url = self::$ip . "/v1/speech";
        $device_codes = \app\common\model\broadcast\IpBroadcast::where("FIND_IN_SET({$param['hk_device_serial_id']}, hk_device_serial_id)")
            ->where(['type' => 1])
            ->column('code');
        if (!empty($device_codes)) {
            //获取当前ip下所有音箱
            json_post($url, [
                'device_codes' => $device_codes,//设备编码数组
                'url' => $param['url'],//播放音频网络地址
                'volume' => 100 //音量
            ], self::$Authorization);
             file_put_contents(public_path().'play_log/play_log.txt', json_encode($device_codes) . $param['hk_device_serial_id'].":" . date('Y-m-d H:i:s') . "\r\n", FILE_APPEND);
        }
    }

    /**
     * 调用远端websocket进行播放广播
     * @param $param
     * @return void
     */
    public static function websocketPlay($param)
    {
        //长链接调用装置播放
        $ip_broadcast = \app\common\model\broadcast\IpBroadcast::whereFindInSet('hk_device_serial_id', $param['hk_device_serial_id'])
            ->where(['type' => 2])
            ->field(['id', 'ip', 'authorization', 'code', 'device_rod_id'])
            ->select()
            ->toArray();
        if (!empty($ip_broadcast)) {
            foreach ($ip_broadcast as $val) {
                $url = "http://127.0.0.1:9501/broadcast";
                json_post($url, [
                    'device_codes' => [$val['code']],
                    'url' => $param['url'],
                    'device_rod_id' => $val['device_rod_id'],
                    'ip' => $val['ip'],
                    'authorization' => $val['authorization']
                ]);
            }
        }
    }
}